<?php
/**
 * 帮助函数
 */

if (!function_exists('test')) {
    function test()
    {
        return "test ok";
    }
}

if (!function_exists('clean_xss')) {
    function clean_xss(&$string, $low = false)
    {
        if (! is_array ( $string )) {
            $string = trim ( $string );
            //$string = strip_tags ( $string );
            $string = htmlspecialchars ( $string );
            if ($low) {
                return true;
            }
            $string = str_replace ( array ('"', "\\", "'", "/", "..", "../", "./", "//" ), '', $string );
            $no = '/%0[0-8bcef]/';
            $string = preg_replace ( $no, '', $string );
            $no = '/%1[0-9a-f]/';
            $string = preg_replace ( $no, '', $string );
            $no = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';
            $string = preg_replace ( $no, '', $string );
            return true;
        }
        $keys = array_keys ( $string );
        foreach ( $keys as $key ) {
            clean_xss ( $string [$key] );
        }
    }
}

if ( ! function_exists('uuid')) {
    /**
     * 获取uuid
     * @return string
     */
    function uuid() : string
    {
        return \Uuid::generate()->string;
    }
}

if ( ! function_exists('unique_key')) {
    /**
     * 获取一个唯一值
     * @return string
     */
    function unique_key() : string
    {
        return md5(uuid());
    }
}

if ( ! function_exists('get_query_log')) {
    /**
     * 打印sql语句
     * @param callable $function
     * @return array
     */
    function get_query_log(callable $function) : array
    {
        \DB::enableQueryLog();
        $function();
        return \DB::getQueryLog();
    }
}

if (!function_exists('rand_code')) {
    /**
     * 生成随机code
     * @param int $length
     * @param string $type
     * @return bool|string
     */
    function rand_code($length = 6, $type = 'code') : string
    {
        $int = '123456789';
        $str = 'abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
        if ($type == 'int') {
            return substr(str_shuffle('0' . $int), 0, $length);
        }
        if ($type == 'str') {
            return substr(str_shuffle($str), 0, $length);
        }
        if ($type == 'code') {
            return substr(str_shuffle($int . $str), 0, $length);
        }
    }
}

if ( ! function_exists('secret_salt')) {
    /**
     * 生成加密salt,但是为了防止 salt由前端传递 在传输过程中防止被窃取最好在传输前再次进行加密
     * @param string $salt
     * @return string
     */
    function secret_salt($salt = 'Encode'): string
    {
        return md5(str_rot13(md5($salt)));
    }
}

if (!function_exists('encode_pwd')) {
    /**
     * 加密密码
     * @param $password
     * @param string $salt
     * @param bool $has_encode
     * @return string
     */
    function encode_pwd($password, $salt='Encode', $has_encode=false) : string
    {
        $password = $has_encode ? $password : md5($password.'_!q1Q☺');
        return md5($password.$salt);
    }
}

if (!function_exists('first_img')) {
    /**
     * 获取内容第一张图片
     * @param $str
     * @return string
     */
    function first_img($str) : string
    {
        $p = "#src=('|\")(.*)('|\")#isU"; # 正则表达式
        preg_match_all ($p, $str, $img);
        return isset($img[2][0]) ? $img[2][0] : ''; # 获取第一张图片路径
    }
}

if (!function_exists('is_end_needle')) {
    /**
     * 以某字符串结尾
     * @param $str
     * @param $needle
     * @return bool
     */
    function is_end_needle($str, $needle) : bool
    {
        if(strrchr($str, $needle) == $needle) {
            return true;
        }
        return false;
    }
}

if (!function_exists('safe_base64_decode')) {
    /**
     * 安全的base64解码
     * @param $str
     * @return bool|string
     */
    function safe_base64_decode($str) : string
    {
        $find = array('-', '_');
        $replace = array('+', '/');
        return base64_decode(str_replace($find, $replace, $str));
    }
}

if (!function_exists('safe_base64_encode')) {
    /**
     * 安全的base64编码
     * @param $data
     * @return mixed
     */
    function safe_base64_encode($data) : string
    {
        $find = array('+', '/');
        $replace = array('-', '_');
        return str_replace($find, $replace, base64_encode($data));
    }
}

if (! function_exists('curl_request')) {
    /**
     * CURL Request
     * @param $api
     * @param string $method
     * @param array $params
     * @param array $headers
     * @return bool|mixed|string
     */
    function curl_request($api, $method = 'GET', $params = array(), $headers = []) : mixed
    {
        $curl = curl_init();

        switch (strtoupper($method)) {
            case 'GET' :
                if (!empty($params)) {
                    $api .= (strpos($api, '?') ? '&' : '?') . http_build_query($params);
                }
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);//如果重定向
                break;
            case 'POST' :
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $params);

                break;
            case 'PUT' :
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
                break;
            case 'DELETE' :
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
                curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
                break;
        }

        curl_setopt($curl, CURLOPT_URL, $api);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HEADER, 0);

        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($curl);

        if ($response === false) {
            $error = curl_error($curl);
            curl_close($curl);
            return false;
        }else{
            $response = trim($response,chr(239).chr(187).chr(191)); # 解决windows 服务器 BOM 问题
            $response = json_decode(str_replace("\r\nct", "", $response), true);
        }

        curl_close($curl);

        return $response;
    }
}

if (!function_exists('show_dir')) {
    /**
     * 目录下文件
     * @param string $dir_name
     * @return array
     */
    function show_dir( $dir_name = '.' ) : array
    {
        $file_arr = [];
        $dir = @ dir($dir_name);
        while (($file = $dir->read())!==false) { # 或while(($file = readdir($dir)) !== false)
            if(is_dir($dir_name . "/" . $file) and $file!='.' and $file!='..') {
                show_dir($dir_name . "/" . $file);
            } else {
                $file_arr[] = $dir_name . "/" . $file;
            }
        }
        $dir->close();
        return $file_arr;
    }
}

if (!function_exists('filter_null')) {
    /**
     * 过滤掉数组中null
     * @param array $arr
     * @return array
     */
    function filter_null(array $arr)
    {
        $newArr = [];
        array_walk($arr,function($val, $key)use(&$newArr){
            if ($val !== null) {
                return $newArr[$key] = $val;
            }
        });
        return $newArr;
    }
}




/**
 *
 */
if (!function_exists('aa')) {

}



